//
//  GameScene.swift
//  FrogGame
//
//  Created by wanght on 2016/12/1.
//  Copyright © 2016年 wanght. All rights reserved.
//

import SpriteKit
import GameplayKit

enum GameStatus : Int {
    case stop = 1, start
}


class GameScene: SKScene {
    
    
    var gameStatus = GameStatus.stop
    // frog current pos index
    var currentIndex = 0
    var resetTime : Int = 2000
    var interval : TimeInterval = 0
    var lastUpdateTime: TimeInterval = 0
    
    var background = Backgound()
    var leaf = Leaf()
    var frogNode = Frog()

    var pauseButton : SKSpriteNode!
    var leftButton : SKSpriteNode!
    var rightButton : SKSpriteNode!
    
    var rankNode : SKSpriteNode!
    var timeLabel : SKLabelNode!
    var stepLabel : SKLabelNode!
    var tipLael : SKLabelNode!
    
    let leftNormalTexture : SKTexture = SKTexture(imageNamed: "button_left_normal")
    let rightNormalTexture : SKTexture = SKTexture(imageNamed: "button_right_normal")
    let leftPressedTexture : SKTexture = SKTexture(imageNamed: "button_left_pressed")
    let rightPressedTexture : SKTexture = SKTexture(imageNamed: "button_right_pressed")

    let appDelegate = (UIApplication.shared.delegate as? AppDelegate)

    override func didMove(to view: SKView) {
        
        frogNode.position = CGPoint(x: 667, y: 305)
        frogNode.zPosition = 10

        addChild(frogNode)
        addChild(background)
        addChild(leaf)
        
        rankNode = self.childNode(withName: "//rankNode") as! SKSpriteNode!
        rankNode.isHidden = true
        
        pauseButton = self.childNode(withName: "//pauseButton") as! SKSpriteNode
        leftButton = self.childNode(withName: "//leftButton") as! SKSpriteNode!
        rightButton = self.childNode(withName: "//rightButton") as! SKSpriteNode!
        
        timeLabel = self.childNode(withName: "//timeLabel") as! SKLabelNode!
        stepLabel = self.childNode(withName: "//stepLabel") as! SKLabelNode!
        tipLael = self.childNode(withName: "//tipLabel") as! SKLabelNode!
    }
    
    
    func touchDown(atPoint pos : CGPoint) {
    }
    
    func touchMoved(toPoint pos : CGPoint) {
    }

    func touchUp(atPoint pos : CGPoint) {
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        
        //only one finger touch
        guard let touch = touches.first else {
            return
        }
        
        if resetTime == 2000 && gameStatus == .stop {
            startGame()
            gameStatus = .start
        } else if gameStatus == .stop {
            gameStatus = .start
            showRank()
        }
        
        tipLael.text = ""
        
        print("frogNode.status  \(frogNode.status) ")
        
        if frogNode.status != .stand {
            return
        }
        
        let touchLocation = touch.location(in: self)
        let touchedNode = self.atPoint(touchLocation)
        
        if touchedNode.name == "leftButton" {
            
            let spriteNode = touchedNode as! SKSpriteNode
            spriteNode.texture = leftPressedTexture
            
        } else if touchedNode.name == "rightButton" {
            
            let spriteNode = touchedNode as! SKSpriteNode
            spriteNode.texture = rightPressedTexture
            
        }

    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        //only one finger touch
        guard let touch = touches.first else {
            return
        }
        
        if frogNode.status != .stand {
            return
        }

        
        let touchLocation = touch.location(in: self)
        let touchedNode = self.atPoint(touchLocation)
        
        
        if touchedNode.name == "leftButton" {
            
            let spriteNode = touchedNode as! SKSpriteNode
            spriteNode.texture = leftNormalTexture
            judgeFrogAnimate(step : 1)
            
        } else if touchedNode.name == "rightButton" {
            
            let spriteNode = touchedNode as! SKSpriteNode
            spriteNode.texture = rightNormalTexture
            judgeFrogAnimate(step : 2)
        }
        
        if touchedNode.name == "pauseButton" {
            pauseGame()
        }
        
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    
    
    
    override func update(_ currentTime: TimeInterval) {

        if gameStatus != .start {
            return
        }
        
        if lastUpdateTime > 0 {
            interval = currentTime - lastUpdateTime
        }
        
        resetTime -= Int(interval * 100)
        
        //if num low 10, need add 0 that make timeLabel is perfect
        let second : Int = resetTime / 100
        let demical : Int = resetTime % 100
        let secondString = (second < 10) ? "0\(second)" :"\(second)"
        let demicalString = (demical < 10) ? "0\(demical)" :"\(demical)"
        
        timeLabel.text = String("\(secondString):\(demicalString)")
        
        if resetTime <= 0 {
            overGame()
        }
        
        lastUpdateTime = currentTime
    }
    
    func judgeFrogAnimate(step: Int) {
        
        currentIndex += step
        stepLabel.text = String("Step: \(currentIndex)")
        
        if leaf.array[currentIndex] == 0 {              //fall water
            
            background.move(stepNumber: -step)
            leaf.move(stepNumber: -step, currentIndex : currentIndex)
            frogNode.jumpWaterFrog()
            
            currentIndex -= step
            
        } else {                                        //normal and get awards
            
            if leaf.array[currentIndex] == 2 {          // get time awards
                //add time on Label
                resetTime += 500
            }
            
            background.move(stepNumber: step)
            leaf.move(stepNumber: step, currentIndex: currentIndex)
            frogNode.jumpFrog()
            
        }
    }

    
    //show rank 
    func showRank() {
        rankNode.isHidden = true
    }
    func hideRank() {
        rankNode.isHidden = false
    }
    
    func pauseGame() {
        
        gameStatus = .stop
        lastUpdateTime = 0

        
        let list = appDelegate?.fetchContext()

        for tempItem in list! {
            let tempInt = (tempItem.step)
            print("temp \(tempInt)")

        }
        
        let resultList = rankSort(list: list!)
        
        for i in 1...resultList.count - 1 {
            let numLabel = rankNode.childNode(withName: "rankNum\(i)") as! SKLabelNode
            numLabel.text = String("\(resultList[i - 1])")
        }
        hideRank()
    }
    
    func rankSort(list: [RankMO]) -> Array<Any> {
        
        var resultList = [Int](repeating: 0, count: 5)
 
        var temp : String = "0"
        var count = list.count
        
        if count <= 2 {
            return resultList
        }
        
        for i in 0...count - 2 {
            for j in 0...(count - 2 - i) {

                let preInt : Int = Int(list[j].step)!
                let proInt : Int = Int(list[j+1].step)!
                print("preInt \(preInt)")
                print("proInt \(proInt)")
                
                if preInt < proInt {
                    temp = list[j].step
                    list[j].step = list[j+1].step
                    list[j+1].step = temp
                }
            }
        }
        
        if count > 5 {
            count = 5
        }
        
        for i in 0...(count - 1) {
            resultList[i] = Int(list[i].step)!
        }
        
        return resultList
    }
    
    //start game initial variable
    func startGame() {
        interval = 0
        lastUpdateTime = 0
        currentIndex = 0
        stepLabel.text = "Step: 0"
    }
    
    // game over modify variable
    func overGame() {
        resetTime = 2000
        gameStatus = .stop
        timeLabel.text = "00:00"
        tipLael.text = "game over! touch screen start"
        appDelegate?.addToContext(step: "\(currentIndex)")
    }
}
